package com.pek.security;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.pek.config.Validate;
import com.pek.control.service.IUserService;
import com.pek.control.util.RedisUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class TokenFilter extends OncePerRequestFilter {

    public TokenFilter(RedisUtil redisUtil, AuthenticationManager authenticationManager) {
        this.redisUtil = redisUtil;
        this.authenticationManager = authenticationManager;
    }

    private RedisUtil redisUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private IUserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String tokenKey = request.getHeader("TOKEN");
        if (StringUtils.isBlank(tokenKey)) {
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        JSONObject user = (JSONObject) redisUtil.get(tokenKey);
        if (user == null || !user.containsKey("user")) {
            filterChain.doFilter(request, response);
            return;
        }
        //获取ip并验证ip是否相同
        if (!(user.containsKey("ip") && user.getString("ip").equals(Validate.getIp()))) {
            logger.info("Error IP : " + Validate.getIp());
            filterChain.doFilter(request, response);
            return;
        }
        //从redis中获取用户信息
        LoginUser loginUser = (LoginUser) user.get("user");
        //存入SecurityContextHolder中
        UsernamePasswordAuthenticationToken authorToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authorToken);
        filterChain.doFilter(request, response);
    }
}
